﻿using MoetutuServer.Helper;
using MoetutuServer.PostHelper;
using MoetutuServer.PublishHelper;
using MoetutuServer.WebSite.Pixiv;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordPressSharp;
using WordPressSharp.Models;

namespace MoetutuServer.Helper.RepairHelper
{
    class ModifyContent
    {

        /// <summary>
        ///读取已发布文章的内容
        /// </summary>
        /// <param name="UserInfoPath">用户信息路径</param>
        /// <returns></returns>
        public static String GetContent(String UserInfoPath, int PostId)
        {
            if (PostId == 0)
            {
                Console.WriteLine("Id不正确");
                return "";
            }
            Console.WriteLine("读取现有文章");
            String ContentText = "";
            using (WordPressClient WpClient = new WordPressClient(UserInfoHelper.ReadUserInfo(UserInfoPath)))
            {
                Post post = WpClient.GetPost(PostId);
                ContentText = post.Content;

            }
            return ContentText;
        }
        /// <summary>
        /// 获取文章内容的入口s
        /// </summary>
        /// <param name="UserDataPath"></param>
        /// <param name="id"></param>
        /// <returns></returns>

        public static string ModifySingle(String UserDataPath,String id) {
            PrintLog.Log("挂载测试信息{0}，ID{1}",UserDataPath,id);
            string Content = GetContent(UserDataPath,TextHelper.StringToInt(id));
            if (Content != "")
            {
                //这是证明图片修正过一次的flag，代表这个文章有过违规内容，如果紧急情况下请监测这个flag清理掉所有违规内容
                String DangerousFlag = "<div class=\"DangerousFlag\"></div>";

                Content =GetNewContent(Content);
                if (Content == null)
                {//有至少一张图片出现空指针
                 
                  WordpressModify.Delete(id, UserDataPath);
                    return "已删除";
                }
                if(Content!="")
                WordpressModify.Edit(id,Content+ DangerousFlag, UserDataPath);
                else
                    Console.WriteLine("无需修改，跳过！");
            }
            else {
                Console.WriteLine("读取文章内容失败！");
            }

            return Content;
          
        }

        internal static void RepairForTag(string UserDataPath, string id)
        {
            PrintLog.Log("挂载测试信息{0}，ID{1}", UserDataPath, id);
            List<string> TempTaglist = new List<string>();
            string Content = GetContent(UserDataPath, TextHelper.StringToInt(id));
            if (Content != "") {
                List<string> Tagtemp = HtmlHelper.GetTextValueList(Content, "//ul[@class='wp-tag-out']/li/a");
                foreach (string line in Tagtemp) {
                    Console.WriteLine("捕获tag"+line);
                    TempTaglist.Add(line.Trim());
                }
                if (TempTaglist.Count > 0) {
                    WordpressModify.AddTag(id, Content, TempTaglist, UserDataPath);
                 
                }
            }
        }

        /// <summary>
        /// 匹配文本并且替换
        /// </summary>
        /// <param name="UserDataPath"></param>
        /// <param name="id"></param>
        /// <param name="OldTextRule"></param>
        /// <param name="NewTxet"></param>

        internal static void ReplaceSingle(string UserDataPath, string id, string OldTextRule, string NewTxet)
        {
            PrintLog.Log("挂载测试信息{0}，ID{1}", UserDataPath, id);
            string Content = GetContent(UserDataPath, TextHelper.StringToInt(id));
            if (Content != "") {
                string RepText = TextHelper.RegexText(Content, OldTextRule);
                if (RepText != "")
                {
                    Console.WriteLine("匹配到：" + RepText);
                   
                    WordpressModify.Edit(id, Content.Replace(RepText, NewTxet), UserDataPath);
                }
                
            }


        }


        /// <summary>
        /// 查找并且替换内容 返回null则代表文章需要删除
        /// </summary>
        /// <param name="Content"></param>
        /// <returns></returns>
        private static string GetNewContent(String Content)
        {
          
            List<string> AllImg = HtmlHelper.GetLinkVlaueList(Content, "//div[@class='Original_img']/a");

            if (AllImg.Count > 0) {


                List<String> InvalidImgList = GetInvalidImg(AllImg);
                if (InvalidImgList == null)//发现空指针了！
                    return null;
                if (InvalidImgList.Count == 0)
                    return ""; //没需要修改的，直接返回
                String OrginImg = GetOriginalImgLink(AllImg, InvalidImgList);//获取原始图片的图片链接

                foreach (string line in InvalidImgList) {

                    Content = ReplaceContent(OrginImg,line,Content);
                }
                return Content;
            }
         
         
            return null;//替换失败的情况！ 
        }
        /// <summary>
        /// 获取没有失效的原图
        /// </summary>
        /// <param name="allImg"></param>
        /// <param name="invalidImgList"></param>
        /// <returns></returns>
        private static string GetOriginalImgLink(List<string> allImg, List<string> invalidImgList)
        {
            string Link = "";
            foreach (string line in allImg) {
                if (line.IndexOf("i.pximg.net") > 0)
                    return line;
                else if (line.IndexOf("zerochan.net") > 0)
                    return line;
                else if (line.IndexOf("konachan.net") > 0||line.IndexOf("konachan.com")>0)
                    return line;
                else if (!invalidImgList.Contains(line))
                    Link = line;
            }
            return Link;
        }

        /// <summary>
        ///获取所有已经失效的链接
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static List<string> GetInvalidImg(List<string> AllImg)
        {
            List<string> TempList = new List<string>();
            foreach (string line in AllImg)
            {
            
                if (line != "")
                {
                    Console.WriteLine(line);
                    if (WebHelper.GetLinkMove(line))
                    {
                        PrintLog.Log("捕获链接{0}失效，类型301", line);

                        TempList.Add(line);
                    }
                }
                else
                {
                    Console.WriteLine(      "捕获到一个空的下载链接"+line);
                    return null;//发现空指针了！形成原因可能是ILOLI返回了一个空指针
                }

              
            }
            return TempList;
        }
        /// <summary>
        /// 替换并且修正链接为可用的
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <param name="ReplaceImgUrl"></param>
        /// <param name="Content"></param>
        public static string ReplaceContent(String ImgUrl, String ReplaceImgUrl, String Content) {
            String Filename = "";
            if (ImgUrl.IndexOf("i.pximg.net") > 0)
                Filename = PixivHelper.PixivDownload(ImgUrl);
            else
              Filename = WebHelper.FileDownload(ImgUrl);
            Console.WriteLine("文件存储路径：{0}",Filename);
          
            if (Filename != "")
            {
             //   ImageHelper.CompressImage(Filename, Filename);//进行一次压缩
                String NewImgLink = ILoli.UploadImgAsync(Filename);
                Console.WriteLine(NewImgLink);
                if (NewImgLink != "")
                    Content = Content.Replace(ReplaceImgUrl, NewImgLink);
                else
                {
                    Console.WriteLine("图床上传失败，删除流程启动");
                    return null;
                }
            }
            else {
                Console.WriteLine("下载失败！");
               
            }

            return Content;
        }
    }
}
